#include "global.h"
#include "constant.h"
#include<cstring>
#include <QUuid>
#include <QDebug>
#include <QNetworkInterface>
#include <QList>


tagReqHead Global::gReqHead;
void Global::GenerateReqSeqno()
{
    memcpy(gReqHead.seq_no, QUuid::createUuid().toByteArray().toStdString().c_str()+1, SEQNO);
}

void Global::Init()
{
    m_bLogSuccess = false;
    InitReqHead();
}

void Global::InitReqHead()
{
    memset(&gReqHead,0x00,sizeof(gReqHead));
    sprintf(gReqHead.msg_type,"%s",gc_sPktTypeTrade.c_str());
    sprintf(gReqHead.msg_flag,"%s",gc_sFlagReq.c_str());
    sprintf(gReqHead.term_type,"%s",gc_sTermTypeManage.c_str());
    sprintf(gReqHead.user_type,"%s",gc_sUserTypeOper.c_str());
}

void Global::ParseServerList(const QString sRsp8006)
{
    m_htm_server_list.Parse(sRsp8006);
    qDebug()<<"save ServerList:"<<m_htm_server_list.ToQStringEx();
}

HashtableMsg Global::GetServerList()
{
    return m_htm_server_list;
}

QString Global::GetHostIpAddress()
{
    QString strIpAddress;
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    // 获取第一个本主机的IPv4地址
    int nListSize = ipAddressesList.size();
    for (int i = 0; i < nListSize; ++i)
    {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
                ipAddressesList.at(i).toIPv4Address())
        {
            strIpAddress = ipAddressesList.at(i).toString();
            break;
        }
    }
    // 如果没有找到，则以本地IP地址为IP
    if (strIpAddress.isEmpty())
        strIpAddress = QHostAddress(QHostAddress::LocalHost).toString();
    return strIpAddress;
}

void Global::SetLoginRsp(RspBase rsp)
{
    m_rsp8001 = rsp;
    m_rsp8001.RemoveItem("alm_menu_info");
    m_tradeDate = QDate::fromString(m_rsp8001.GetQStringPara("exch_date"),"yyyyMd");

    QTime current_time = QTime::currentTime();
    m_tradeDate.fromString(m_rsp8001.GetQStringPara("exch_date"),"yyyyMd");
    QTime tradeTime = QTime::fromString(m_rsp8001.GetQStringPara("exch_time"),"hh:mm:ss");
//    m_offsetTradeTime = tradeTime.secsTo(current_time);
    m_offsetTradeTime = current_time.secsTo(tradeTime);
    qDebug()<<"m_tradeDate:"<<m_tradeDate.toString()<<" tradeTime:"<<tradeTime.toString()<<" current_time:"<<current_time.toString()<<" m_offsetTradeTime"<<m_offsetTradeTime;
}

QString Global::GetParaFrom8001(const QString sKey)
{
    return m_rsp8001.GetQStringPara(sKey);
}

QString Global::GetTradeTime()
{
    QTime current_time = QTime::currentTime();
    QTime tTime = current_time.addSecs(m_offsetTradeTime);
//    qDebug()<<"current_time:"<<tTime.toString()<<" m_offsetTradeTime"<<m_offsetTradeTime;
    return QDateTime(m_tradeDate, tTime).toString();
}
